import { createRouter, createWebHistory } from 'vue-router'
import Login from '@/views/Login.vue'
import Register from '@/views/Register.vue'
import Teacher from '@/views/Teacher.vue'
import Student from '@/views/Student.vue'
import DataManager from '@/views/DataManager.vue'
import { useAuthStore } from '@/stores/auth'

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/',
      redirect: '/login'
    },
    {
    path: '/login',
    name: 'Login',
    component: Login
  },
  {
    path: '/register',
    name: 'Register',
    component: Register
  },
    {
      path: '/teacher',
      name: 'Teacher',
      component: Teacher,
      meta: { requiresAuth: true, role: 'teacher' }
    },
    {
      path: '/student',
      name: 'Student',
      component: Student,
      meta: { requiresAuth: true, role: 'student' }
    },
    {
      path: '/data',
      name: 'DataManager',
      component: DataManager,
      meta: { requiresAuth: false }
    }
  ],
})

// 路由守卫
router.beforeEach((to, from, next) => {
  const authStore = useAuthStore()
  
  if (to.meta.requiresAuth) {
    if (!authStore.isLoggedIn) {
      next('/login')
    } else if (to.meta.role && authStore.userRole !== to.meta.role) {
      // 角色不匹配，跳转到对应角色的页面
      if (authStore.userRole === 'teacher') {
        next('/teacher')
      } else if (authStore.userRole === 'student') {
        next('/student')
      } else {
        next('/login')
      }
    } else {
      next()
    }
  } else {
    next()
  }
})

export default router
